<include file="Public:header" />
<script type="text/javascript" src="__PUBLIC__/js/PCASClass.js" ></script>
<style type="text/css">
.add_body >div >.full-height-scroll{
   	border-right:1px dotted #ccc
}
.add_body_title{
	margin:20px 0 0 10px;
	padding-left: 14px;
}
.add_body_form>form>.form-group{
	margin-bottom: 25px;
}
body{overflow-y:hidden;}
.product_thead>tr>td{
	background-color:#FFFFFF;padding:1px;font-size:13px;color:#999;
}
/*附件样式*/
.test_div {
    width: 98.8%;
    background-color: #f9f9f9;
    height: 30px;
    position: relative;
    top: -31px;
    right: -1px;
}
.test_div>.addfile{
	display: inline-block;
    line-height: 30px;
    margin-left: 18px;
    cursor: pointer;
}
#filecontent{
	width: 95%;
    border: 1px dashed #d8e3ef;
}
.showfile{
	padding:6px;
}
#filecontent .tishiinfo{
	margin-top: 10px;
    margin-bottom: 10px;
    display: block;
    margin-left: 10px;
}
#filecontent .fujian{
	margin-left: 8px;
	color: #646464;
}
#addfilediv{
	color: #cccccc;
    margin-left: 6px;
    padding-top: 8px;
    display: block;
    margin-bottom: 6px;
}
.file_list{
    margin-top: 10px;
}
</style>
<script>
$(function(){
	$(".add_body").height(window.innerHeight-$("#add_body").offset().top-$("#tfoot_div").height()-40);
	$(window).resize(function(){
		$(".add_body").height(window.innerHeight-$("#add_body").offset().top-$("#tfoot_div").height()-40);
	})
})
</script>
<div class="wrapper wrapper-content animated fadeIn">
	<include file="Public:alert" />
	<form class="form-horizontal" id="form" role="form" action="{:U('contract/add')}" method="post" enctype="multipart/form-data">
		<input type="hidden" name="refer_url" value="{$refer_url}" />
		<input type="hidden" name="total_amount_val" id="total_amount" value="0" />
		<input type="hidden" name="renew_contract_id" value="{$old_contract_id}">
		<input type="hidden" name="renew_parent_id" value="{$renew_parent_id}">
		<div class="ibox-content add_body" id="add_body" >
			<div class="row">
				<div class="col-md-6 add_body" style="padding-right: 0px;">
					<div class="full-height-scroll">
						<div class="row">
							<div class="col-md-12 add_body_title" >
								<div class="all-inline">
									<span class="sq-tag"></span>
									<div class="text-tag">
										<span>基础信息</span>
									</div>
								</div>
							</div>
							<div class="col-md-11 add_body_form" style="margin:20px 0 0 20px;">
								<volist name="field_list['main']" id="vo" key="key">
									<if condition="$vo['field'] eq 'customer_id'">
										<div class="form-group">
											<label class="col-md-4 control-label">{:L('SOURCE_OF_CUSTOMERS')}：</label>
											<div class="col-md-6">
												<input type="hidden" name="customer_id" id="customer_id" value="{$contract_info.customer_id}" />
												<input class="form-control required" aria-required="true" placeholder="请点击选择" type="text" name="customer_name" id="customer_name" value="{$contract_info.customer_name}" readonly="true" style="cursor:pointer;" title="请点击选择"/>
											</div>
											<div class="col-md-2"><span style="color:red">*</span></div>
										</div>
									<elseif condition = "$vo['field'] eq 'business_id'" />
										<if condition="$old_contract_id">
											<div class="form-group" style="display: none">
												<label class="col-md-4 control-label">来源项目：</label>
												<div class="col-md-6">
													<input type="hidden" name="business_id" value=""/>
													<input class="form-control" type="text" name="business_name" value="" readonly="true" style="cursor:pointer;" />
												</div>
												<div class="col-md-2"></div>
											</div>
										<else/>
											<div class="form-group" style="display: block">
												<label class="col-md-4 control-label">项目编号：</label>
												<div class="col-md-6">
													<input type="hidden" name="business_id" id="business_id" value="{$contract_info.business_id}"/>
													<input class="form-control" placeholder="请点击选择" type="text" name="business_name" id="business_name" value="{$contract_info.business_name}" readonly="true" style="cursor:pointer;" title="请点击选择"/>
												</div>
												<div class="col-md-2"></div>
											</div>
										</if>
									<elseif condition = "$vo['field'] eq 'contract_name'" />
										<div class="form-group">
											<label class="col-md-4 control-label">{:L('CONTRACT_NO')}：</label>
											<div class="col-md-6">
												<div class="input-daterange input-group">
													<span class="input-group-addon" style="background-color:#ccc;">{$contract_custom}</span>
													<input type="text" id="number" name="number" rel="require" readonly="readonly" class="form-control checkit" value="{$number}"/>
													<input type="hidden" id="prefixion" name="prefixion" value="{$contract_custom}"/>
												</div>
											</div>
											<div class="col-md-2"><span style="color:red">*</span></div>
										</div>
										<div class="form-group">
											<label class="col-md-4 control-label" >合同名称：</label>
											<div class="col-md-6">
												<input class="form-control required" aria-required="true" type="text" name="contract_name" value="<if condition='$contract_info[contract_name]'>续约《{$contract_info['contract_name']}》</if>" id="contract_name" />
											</div>
											<div class="col-md-2"><span style="color:red">*</span></div>
										</div>
										<div class="form-group">
											<label class="col-md-4 control-label">合同签约人：</label>
											<div class="col-md-6">
												<input type="hidden" name="owner_role_id" id="owner_id" value="{$Think.session.role_id}"/>
												<input class="form-control required" aria-required="true" type="text" name="owner_role_name" id="owner_name" value="{$Think.session.full_name}" readonly="true" style="cursor:pointer;" title="请点击选择"/>
											</div>
											<div class="col-md-2"><span style="color:red">*</span></div>
										</div>
									<elseif condition = "$vo['field'] eq 'price'" />
										<div class="form-group">
											<label class="col-md-4 control-label">合同金额(元)：</label>
											<div class="col-md-6">
												<input class="form-control required" type="text" id="contract_price" name="price" value="{$contract_info['final_price']}" placeholder="如：20000" onblur="bu(this)" onkeyup="final_price_sum('contract_price');"/>
											</div>
											<div class="col-md-2"><span style="color:red">*</span></div>
										</div>
									<elseif condition = "$vo['field'] eq 'start_date'" />
										<div class="form-group">
											<label class="col-md-4 control-label">{:L('THE_TIME_WHICH_THE_CONTRACT_COMES_INTO_FORCE')}：</label>
											<div class="col-md-6">
												<input class="form-control required Wdate" aria-required="true" type="text" id="start_date" name="start_date" onFocus="WdatePicker({dateFmt:'yyyy-MM-dd', maxDate:&quot;#F{$dp.$D('end_date')||'2038-01-01'}&quot;})" value="<?php echo date('Y-m-d', time());?>" />
											</div>
											<div class="col-md-2"><span style="color:red">*</span></div>
										</div>
									<elseif condition = "$vo['field'] eq 'end_date'" />
										<div class="form-group">
											<label class="col-md-4 control-label">{:L('CONTRACT_TIME')}：</label>
											<div class="col-md-6">
												<input class="form-control required Wdate" aria-required="true" type="text" id="end_date" onFocus="WdatePicker({dateFmt:'yyyy-MM-dd', minDate:&quot;#F{$dp.$D(\'start_date\')}&quot;,maxDate:'2038-01-01'})" name="end_date" />
											</div>
											<div class="col-md-2"><span style="color:red">*</span></div>
										</div>
									<else />

										<div class="form-group">
											<label class="col-md-4 control-label">{$vo.name}：</label>
											<if condition="$vo['form_type'] == 'textarea'">
												<if condition = "$vo['tip_start'] eq 1">
													<div class="col-md-6">
														<textarea class="form-control" rows="5"></textarea>
													</div>
													<div class="col-md-2"><span style="color: red;line-height: 32px;margin-left: 10px;">*</span></div>
												<else/>
													<!--备注--------------------------------------------------------------------------------------------------------------------------->
													<div class="col-md-8">
														<textarea class="form-control" rows="5" name="description"></textarea>
													</div>
												</if>
											<elseif condition="$vo['form_type'] == 'address'"/>
												<if condition = "$vo['tip_start'] eq 1">
													<div class="col-md-7">
														{$vo.html}
													</div>
													<div class="col-md-1"><span style="color: red;line-height: 32px;margin-left: 10px;">*</span></div>
												<else/>
													<div class="col-md-8">
														{$vo.html}
													</div>
												</if>
											<elseif condition="$vo['form_type'] == 'box'"/>
												<div class="col-md-6">
													{$vo.html}
												</div>
												<if condition = "$vo['tip_start'] eq 1">
													<div class="col-md-2"><span style="color: red;line-height: 32px;margin-left: 10px;">*</span></div>
												<else/>
													<div class="col-md-2"></div>
												</if>
											<else/>
												<div class="col-md-6">
													{$vo.html}
												</div>
												<if condition = "$vo['tip_start'] eq 1">
													<div class="col-md-2"><span style="color: red;line-height: 32px;margin-left: 10px;">*</span></div>
												<else/>
													<div class="col-md-2"></div>
												</if>
											</if>
										</div>
									</if>
								</volist>
								<div class="form-group">
									<label class="col-md-4 control-label">合同附件：</label>

                                    <div class="col-md-6">
                                        <!--<input type="file" id="file_btn" style="display: none">-->
                                        <input type="button" class="btn btn-primary addfile" name="submit_file" value="+上传合同附件"><br>
                                        <div class="file_list"></div>
                                    </div>
                                    <div class="col-md-2"><span style="color: red;line-height: 32px;margin-left: 10px;">*</span></div>
                                    <div class="col-md-12 ibox-content" style="border:0px;">
                                        <div id="filecontent" class="hide">
                                            <span class="tishiinfo"><img src="/Public/img/addFile.png"><span class="fujian">附件</span></span>
                                            <span id="addfilediv">本次共添加了<span id="file_num"></span>文件,总大小<span id="file_size"></span>KB&nbsp;<a href="javascript:;" style="color: #5a8ee2;" onclick="delall();">全部删除</a></span>
                                        </div>
                                    </div>
								</div>
							</div>
							<if condition = "$field_list['data']">
								<div class="col-md-12 add_body_title">
									<div class="all-inline">
										<span class="sq-tag"></span>
										<div class="text-tag">
											<span>附加信息</span>
										</div>
									</div>
								</div>
							</if>
							<div class="col-md-11 add_body_form" style="margin:20px 0 0 20px;">
								<volist name="field_list['data']" id="vo" key="key">
									<div class="form-group">
										<label class="col-md-4 control-label">{$vo.name}：</label>
										<if condition="$vo['form_type'] == 'address' || $vo['form_type'] == 'box' || $vo['form_type'] == 'textarea'">
											<div class="col-md-7">
												{$vo.html}
											</div>
											<if condition = "$vo['tip_start'] eq 1">
												<div class="col-md-1"><span style="color: red;line-height: 32px;margin-left: 10px;">*</span></div>
											<else/>
												<div class="col-md-1"></div>
											</if>
										<else/>
											<div class="col-md-6">
												{$vo.html}
											</div>
											<if condition = "$vo['tip_start'] eq 1">
												<div class="col-md-2"><span style="color: red;line-height: 32px;margin-left: 10px;">*</span></div>
											<else/>
												<div class="col-md-2"></div>
											</if>
										</if>
									</div>
								</volist>
							</div>
							<div class="col-md-1 pull-right">
							</div>
						</div>
					</div>
				</div>
				<div class="col-md-6 add_body" style="padding-left: 0px;display: none;">
					<div class="full-height-scroll">
						<div class="col-md-12 add_body_title" >
							<div class="pull-left">
								<div class="all-inline">
									<span class="sq-tag"></span>
									<div class="text-tag">
										<span>产品信息</span>
									</div>
								</div>
							</div>
							<div class="pull-right">
								<a href="javascript:void(0);" style="padding-top:10px;" id="choseProduct" class="addproduct" >请选择产品</a>
							</div>
						</div>
						<div class="col-md-12 ibox-content" style="border:0px;">
							<div class="panel-body" style="padding:0px;">
								<table class="table table-bordered" id="no-input-border" width="95%" border="0" cellspacing="1" cellpadding="0">
									<thead class="product_thead">
										<tr style="background-color:#FFFFFF;text-align:center;">
											<td>&nbsp;</td>
											<td >产品名称</td>
											<td >价格(元)</td>
											<td >折扣(%)</td>
											<td >销售单价(元)</td>
											<td >数量</td>
											<td >单位</td>
											<td >小计</td>
										</tr>
									</thead>
									<?php $max_key = 1;?>
									<if condition="$contract_info['business_product_list']">
										<tbody>
											<volist name="contract_info['business_product_list']" id="vo">
												<tr id="row_{$key+1}">
													<td style="text-align:center;">
														<a href="javascript:void(0);" class="reduce_one"><i class="icon-minus"></i></a>
													</td>
													<td>
														<input type="hidden" name="business[product][{$key+1}][product_id]" id="product_id_{$key+1}" class="cproduct_id" value="{$vo.product_id}"/>
														<input type="text" class="form-control" id="product_name_{$key+1}" style="border:none;!important" readonly="true" value="{$vo.product_name}"/>
													</td>
													<td><!-- 原价 -->
														<input type="text" id="product_ori_price_{$key+1}" name="business[product][{$key+1}][ori_price]" class="form-control" style="border:none;!important" readonly="readonly"  value="{$vo.ori_price}" />
													</td>
													<td><!-- 折率 -->
														<input type="text" name="business[product][{$key+1}][discount_rate]" id="product_discount_rate_{$key+1}" style="" class="form-control" onkeyup="calculate({$key+1},1)" <if condition="$vo['discount_rate'] eq 0">value="0.00"<else/>value="{$vo.discount_rate}"</if>/>
													</td>
													<td>
														<input type="text" class="form-control" name="business[product][{$key+1}][unit_price]" id="product_unit_price_{$key+1}" onkeyup="calculate({$key+1})" style="" value="{$vo.unit_price}" />
													</td>
													<td><!-- 商品数量 -->
														<input type="text" class="form-control amount" name="business[product][{$key+1}][amount]" style="" id="product_amount_{$key+1}" onkeyup="calculate({$key+1})" value="{$vo.amount}"/>
													</td>
													<td>
														<input type="text" style="border:none;!important" name="business[product][{$key+1}][unit]" readonly="readonly" class="form-control" value="{$vo.unit}"/>
													</td>
													<td><!-- 小计 -->
														<input type="text" style="border:none;!important" name="business[product][{$key+1}][subtotal]" id="product_subtotal_{$key+1}" class="form-control subtotal" value="{$vo.subtotal}" readonly="readonly" rel="{$key+1}"/>
													</td>
												</tr>
												<?php $max_key = ++$key;?>
											</volist>
										</tbody>
									<else/>
										<tbody id="view_row">
											<tr ><td colspan="10" style="color:#999;text-align:center"><span >暂无产品信息，请添加产品！</span></td></tr>
										</tbody>
									</if>
									<tbody id="add_products">
									</tbody>
								</table>
								<div class="ibox" style="overflow-x: hidden;margin: 10px 5px 0px;">
									<div class="row" style="margin: 10px 5px 0px;">
										<div class="col-md-4" style="padding-top:9px">
											产品合计(元):&nbsp;
											<span id="total_subtotal_val">{$contract_info['sales_info']['prime_price']}</span>
											<input type="hidden" value="{$contract_info['sales_info']['prime_price']}" id="prime_price" name="prime_price">
										</div>
										<div class="col-md-4">整单折扣(%):&nbsp;
											<input style="display: inline-block; width: 60px; padding: 1px;" type="text" id="final_discount_rate" name="final_discount_rate" class="form-control" onkeyup="final_price_sum('rate');" value="{$contract_info['sales_info']['final_discount_rate']}" />
										</div>
										<div class="col-md-4">合同金额(元):&nbsp;
											<input style="display: inline-block; width: 100px; padding: 1px;" type="text" name="final_price" id="final_price" class="form-control" placeholder="0.00" onkeyup="final_price_sum('price');" value="{$contract_info['final_price']}" onblur="bu(this)" />
											<input type="hidden" id="total_amount_val" value="{$contract_info['total_amount']}" name="total_amount">
										</div>
									</div>
								</div>
							</div>
						</div>
						<div class="col-md-12 add_body_title" >
							<div class="pull-left">
								<div class="all-inline">
									<span class="sq-tag"></span>
									<div class="text-tag">
										<span>附件信息</span>
									</div>
								</div>
							</div>
							<div class="pull-right">
								<a href="javascript:void(0);" style="padding-top:10px;" class="addfile" >请选择附件</a>
							</div>
						</div>
						<div class="col-md-12 ibox-content" style="border:0px;">
							<!--<div id="filecontent" class="hide">-->
								<!--<span class="tishiinfo"><img src="__PUBLIC__/img/addFile.png"/><span class="fujian">附件</span></span>-->
								<!--<span id="addfilediv">本次共添加了<span id="file_num"></span>文件,总大小<span id="file_size"></span>KB&nbsp;<a href="javascript:;" style="color: #5a8ee2;" onclick="delall();">全部删除</a></span>-->
							<!--</div>-->
						</div>
					</div>
				</div>
			</div>
		</div>
		<div id="tfoot_div" class="clearfix">
			<div class="clearfix" id="tfoot_page">
				<div class="ibox-content" style="border-top: none;">
					<div class="col-sm-offset-2">
						<button type="submit" id="save_submit" class="btn btn-primary">保存合同</button>
						<input class="btn btn-default" type="button" onclick="javascript:history.go(-1)" value="{:L('RETURN')}"/>
					</div>

				</div>

			</div>
		</div>
	</form>
</div>
<div class="" style="display:none;" id="dialog-validate" title="{:L('TEST_RESULTS')}">
	{:L('HAVE_THE_FOLLOWING_PRODUCTS_ARE_SIMILAR_TO_THE_PRODUCT_NAME')}
	<div id="search_content"></div>
</div>
<div style="display:none;"  id="dialog-customer" title="{:L('SELECT_BUSINESS_OPPORTUNITIES')}">
	<div class="spiner-example">
		<div class="sk-spinner sk-spinner-three-bounce">
			<div class="sk-bounce1"></div>
			<div class="sk-bounce2"></div>
			<div class="sk-bounce3"></div>
		</div>
	</div>
</div>
<div style="display:none;"  id="dialog-customer-list" title="{:L('SELECT_CUSTOMER')}">
	<div class="spiner-example">
		<div class="sk-spinner sk-spinner-three-bounce">
			<div class="sk-bounce1"></div>
			<div class="sk-bounce2"></div>
			<div class="sk-bounce3"></div>
		</div>
	</div>
</div>
<div style="display:none;"  id="dialog-role-list2" title="{:L('SELECT_HEAD')}">
	<div class="spiner-example">
		<div class="sk-spinner sk-spinner-three-bounce">
			<div class="sk-bounce1"></div>
			<div class="sk-bounce2"></div>
			<div class="sk-bounce3"></div>
		</div>
	</div>
</div>
<div style="display:none" id="dialog-product-list" title="添加产品">
	<div class="spiner-example">
		<div class="sk-spinner sk-spinner-three-bounce">
			<div class="sk-bounce1"></div>
			<div class="sk-bounce2"></div>
			<div class="sk-bounce3"></div>
		</div>
	</div>
</div>
<div style="display:none;" id="dialog-file" title="添加文件">
	<div class="spiner-example">
		<div class="sk-spinner sk-spinner-three-bounce">
			<div class="sk-bounce1"></div>
			<div class="sk-bounce2"></div>
			<div class="sk-bounce3"></div>
		</div>
	</div>
</div>
<script type="text/javascript">
	$('#number').blur(function(){
		var number = $(this).val();
		var prefixion = $('#prefixion').val();
		var contract_id = "";
		$.ajax({
			type: "post",
			async:false,
			url: "{:U('contract/yanchong')}",
			data: {number:number,contract_id:contract_id,prefixion:prefixion},
			dataType: "json",
			success : function(result){
				if(result.status != 1){
					swal('合同编号不能重复！','',"error");
					return false;
				}else{
					return true;
				}
			}
		});
	});
	$(document).ready(function(){
		$('#save_submit').prop('disabled',false);
		/*form表单验证*/
		$("#form").validate({
			submitHandler:function(form){
	            $('#save_submit').click(function(){
					$('#save_submit').prop('disabled',true);
				});
	            form.submit();
	        }
		});
	});
	$(function(){
		$(document).on('click','#business_name',function () {
			var customer_id = $('#customer_id').val();
			$('#dialog-customer').dialog('open');
			$('#dialog-customer').load('{:U("customer/clistDialog","customer_id=")}'+customer_id);
		});
		$('#owner_name').click(function () {
			$('#dialog-role-list2').dialog('open');
			$('#dialog-role-list2').load('{:U("user/listDialog")}');
			return false;
		});
		$(document).on('click','#customer_name',function () {
			$('#dialog-customer-list').dialog('open');
			$('#dialog-customer-list').load('{:U("customer/listDialog")}');
		});
	});
	$("#dialog-role-list2").dialog({
		autoOpen: false,
		modal: true,
		width: 800,
		maxHeight: 400,
		buttons: {
			"确定": function () {
				var item = $('input:radio[name="owner"]:checked').val();
				var name = $('input:radio[name="owner"]:checked').attr('rel');
				$('#owner_id').val(item);
				$('#owner_name').val(name);
				$(this).dialog("close");
			},
			"取消": function () {
				$(this).dialog("close");
			}
		},
		position: ["center", 100],
		close:function(){
			$(this).html('');
		}
	});

	$("#dialog-customer").dialog({
		autoOpen: false,
		modal: true,
		width: 800,
		maxHeight: 400,
		buttons: {
			"确定": function () {
				var item = $('input:radio[name="customer"]:checked').val();
				var name = $('input:radio[name="customer"]:checked').parent().parent().next().html();
				var business_id = $('input:radio[name="customer"]:checked').parent().next().attr('value');
				var business_name = $('input:radio[name="customer"]:checked').parent().next().next().next().next().attr('value');
				$('#customer_id').val(item);
				$('#customer_name').val(name);
				$('#business_id').val(business_id);
				$('#business_name').val(business_name);

				//清空产品信息
				$('#add_products').html("");
				now_rows = 0;
				//追加产品信息
				$(".se_product_"+business_id).each(function(){
					now_rows += 1;
					var product_name = $(this).children("input:first-child").val();
					$('#view_row').remove();
					var product_id = $(this).attr('rel');
					var muns = 0;
					if(muns == 0){
						var ori_price = $(this).children("input:first-child").next().val();
						var discount_rate = $(this).children("input:first-child").next().next().val();
						var unit_price = $(this).children("input:first-child").next().next().next().val();
						var amount = $(this).children("input:first-child").next().next().next().next().val();
						var unit = $(this).children("input:first-child").next().next().next().next().next().val();
						var category_name = $(this).children("input:first-child").next().next().next().next().next().next().val();
						if(product_id != null){
							$('#product_name_'+now_rows).val(product_name);
							$('#add_products').append("<tr id='row_"+now_rows+"'><td style='text-align:center;'><a href='javascript:void(0);' class='reduce_one'><i class='icon-minus'></i></a></td><td><input type='hidden' name='business[product]["+now_rows+"][product_id]' id='product_id_"+now_rows+"' class='cproduct_id' value='"+product_id+"' /><input type='text' class='form-control' readonly='true' id='product_name_"+now_rows+"' style='border:none;!important' readonly='readonly' value='"+product_name+"'/></td><td><input type='text' id='product_ori_price_"+now_rows+"' name='business[product]["+now_rows+"][ori_price]' class='form-control' style='border:none;!important' readonly='readonly'  value='"+ori_price+"' /></td><td><input type='text' class='form-control product_discount_rate' name='business[product]["+now_rows+"][discount_rate]' id='product_discount_rate_"+now_rows+"' onkeyup='calculate("+now_rows+",1)' value='"+discount_rate+"'/></td><td><input type='text' class='form-control' name='business[product]["+now_rows+"][unit_price]' id='product_unit_price_"+now_rows+"' onkeyup='calculate("+now_rows+")' value='"+unit_price+"' /></td><td><input type='text' class='form-control amount' name='business[product]["+now_rows+"][amount]' id='product_amount_"+now_rows+"' onkeyup='calculate("+now_rows+")' value='"+amount+"'/></td><td><input type='text' style='border:none;!important' name='business[product]["+now_rows+"][unit]' readonly='readonly' class='form-control' value='"+unit+"'/></td><td><input type='text' class='form-control subtotal' name='business[product]["+now_rows+"][subtotal]' id='product_subtotal_"+now_rows+"' style='border:none;!important' readonly='readonly' rel='"+now_rows+"'/></td></tr>");
							calculate(now_rows);
						}
					}
				});
				$(this).dialog("close");
			},
			"取消": function () {
				$(this).dialog("close");
			}
		},
		position: ["center", 100],
		close:function(){
			$(this).html('');
		}
	});

	$("#dialog-customer-list").dialog({
		autoOpen: false,
		modal: true,
		width: 800,
		maxHeight: 400,
		position: ["center", 100],
		buttons: {
			"确定": function () {
				var item = $('input:radio[name="customer"]:checked').val();
				var name = $('input:radio[name="customer"]:checked').parent().next().html();
				$('#customer_id').val(item);
				$('#customer_name').val(name);
				$('#business_id').val('');
				$('#business_name').val('');
				$(this).dialog("close");
			},
			"取消": function () {
				$(this).dialog("close");
			}
		},
		close:function(){
			$(this).html('');
		}
	});
</script>
<script type="text/javascript">
	var now_rows = {$max_key};
	var total_row_id = {$max_key};
	//减少一条信息
	$(document).on('click','.reduce_one',function(){
		var row_id = $(this).parent().parent().attr('id');
		row_val = row_id.substr(4);
		if($('#product_id_'+row_val).val() == ''){
			$('#'+row_id).remove();
			calculate(total_row_id);
		}else{
			swal({
				title: "温馨提示",
				text: "您确定要移除该商品吗?",
				type: "warning",
				showCancelButton: true,
				confirmButtonColor: "#DD6B55",
				confirmButtonText: "是的，我要移除！",
	       		cancelButtonText:'让我再考虑一下…',
				closeOnConfirm:false,
	        	closeOnCancel:false
	        },
	        function(isConfirm){
				if (isConfirm) {
					$('#'+row_id).remove();
					calculate(total_row_id);
					swal("移除成功！", "您已经移除了该商品信息！", "success");
				} else {
					// return false;
					swal("已取消","您取消了移除操作！","error");
				}
			});
		}
		// now_rows --;
	});

	$(".addproduct").click(function(){
    	$('#dialog-product-list').dialog('open');
        $('#dialog-product-list').load('{:U("product/mutildialog")}');
    });
	//商品浮动层
	$("#dialog-product-list").dialog({
		autoOpen: false,
		modal: true,
		width: 850,
		maxHeight: 500,
		position: ["center",100],
		buttons:{
			'{:L("OK")}':function(){
				$(".se_product").each(function(){
					now_rows += 1;
					var product_name = $(this).text();
					$('#view_row').remove();
					var product_id = $(this).attr('rel');
					var muns = 0;
					$('.cproduct_id').each(function(k, v){
						if($(v).val() == product_id){
							alert_crm('此产品已经存在，如需添加请直接修改数量!');
							muns += 1;
						}
					});
					if(muns == 0){
						var unit_price = $(this).children("input:first-child").val();
						var category_name = $(this).children("input:first-child").next().next().next().val();
						var standard = $(this).children("input:first-child").next().val();
						if(product_id != null){
							$('#product_name_'+now_rows).val(product_name);
							$('#add_products').append("<tr id='row_"+now_rows+"'><td style='text-align:center;'><a href='javascript:void(0);' class='reduce_one'><i class='icon-minus'></i></a></td><td><input type='hidden' name='business[product]["+now_rows+"][product_id]' id='product_id_"+now_rows+"' class='cproduct_id' value='"+product_id+"' /><input type='text' class='form-control' readonly='true' id='product_name_"+now_rows+"' style='border:none;!important' readonly='readonly' value='"+product_name+"'/></td><td><input type='text' id='product_ori_price_"+now_rows+"' name='business[product]["+now_rows+"][ori_price]' class='form-control' style='border:none;!important' readonly='readonly'  value='"+unit_price+"' /></td><td><input type='text' class='form-control product_discount_rate' name='business[product]["+now_rows+"][discount_rate]' id='product_discount_rate_"+now_rows+"' onkeyup='calculate("+now_rows+",1)' value='0.00'/></td><td><input type='text' class='form-control' name='business[product]["+now_rows+"][unit_price]' id='product_unit_price_"+now_rows+"' onkeyup='calculate("+now_rows+")' style='' value='"+unit_price+"' /></td><td><input type='text' class='form-control amount' name='business[product]["+now_rows+"][amount]' id='product_amount_"+now_rows+"' onkeyup='calculate("+now_rows+")' value='1'/></td><td><input type='text' style='border:none;!important' name='business[product]["+now_rows+"][unit]' readonly='readonly' class='form-control' value='"+standard+"'/></td><td><input type='text' class='form-control subtotal' name='business[product]["+now_rows+"][subtotal]' id='product_subtotal_"+now_rows+"' style='border:none;!important' readonly='readonly' rel='"+now_rows+"'/></td></tr>");
							calculate(now_rows);
						}
					}
				});
				$(this).dialog('close');
			},
			'{:L("CANCEL")}':function(){
				$(this).dialog('close');
			}
		},
		close:function(){
			$(this).html('');
		}
	});
	//根据选项计算价格
	function calculate(param,par){
		par = par || 0;
		if($('#product_id_'+param).val() != '' && $('#product_id_'+param).val() != '0'){

			//先对当前Row进行计算
			var amount = $('#product_amount_'+param).val();//数量
			if (typeof(amount) != 'undefined' ) {
				//过滤数量
				amount = amount.replace(/\D/g,''); //清除"数字"和"."以外的字符
			}

			$('#product_amount_'+param).val(amount);

			//产品单价
			var ori_price = $('#product_ori_price_'+param).val();

			//产品售价
			var unit_price = $('#product_unit_price_'+param).val();
			if (typeof(unit_price) != 'undefined' ) {
				//过滤售价
				unit_price = unit_price.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
				unit_price = unit_price.replace(/^\./g,""); //验证第一个字符是数字
				unit_price = unit_price.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
				unit_price = unit_price.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
				unit_price = unit_price.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
			}
			$('#product_unit_price_'+param).val(unit_price);

			//产品折扣
			var discount = $('#product_discount_rate_'+param).val();
			if (typeof(discount) != 'undefined' ) {
				//过滤折扣
				discount = discount.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
				discount = discount.replace(/^\./g,""); //验证第一个字符是数字
				discount = discount.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
				discount = discount.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
				discount = discount.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
			}
			$('#product_discount_rate_'+param).val(discount);

			if( discount != 0){
				var discount_rate = $('#product_discount_rate_'+param).val();
			}else{
				var discount_rate = $('#discount_rate').val();
			}
			discount_rate = new Number(discount_rate);
			var product_discount = cal_discount_money(unit_price, amount);//折扣额
			var unit_val = 0.00;
			if(par == 0){
				if(ori_price == 0 || ori_price == 0.00){
					discount_rate = '0.00';
				}else{
					discount_rate = parseFloat((ori_price-unit_price)/ori_price*100).toFixed(2);
					if(unit_price == 0 || unit_price == 0.00){
						discount_rate = '100.00';
					}
				}
				unit_val = unit_price;
				$('#product_discount_rate_'+param).val(discount_rate);
				var subtotal = parseFloat(unit_val*amount).toFixed(2); //小计
			}else{
				if(discount_rate > 0){
					discount_rate = parseFloat(discount_rate/100).toFixed(2);
					var unit_val = parseFloat(ori_price*(1-discount_rate)).toFixed(2);
				}else{
					var unit_val = parseFloat(ori_price).toFixed(2);
				}
				$('#product_unit_price_'+param).val(unit_val);
				var subtotal = parseFloat(unit_val*amount).toFixed(2); //小计
			}
			$('#product_subtotal_'+param).val(subtotal);
			$('#product_discount_'+param).val(product_discount);
			//合计数量
			var total_amount = 0;
			$('.amount').each(function(k, v){
				if($(v).val() != '' ||  $(v).val() != '0'){
					total_amount += new Number($(v).val());
				}
			});
			$('#total_amount_val').html(total_amount);
			$('#total_amount').val(total_amount);

			//合计小计
			var total_subtotal = 0.00;
			$('.subtotal').each(function(k, v){
				if($(v).val() != '' ||  $(v).val() != '0'){
					total_subtotal += new Number($(v).val());
				}
			});
			//alert(total_subtotal);
			$('#total_subtotal_val').text(total_subtotal.toFixed(2));
			$("#prime_price").val(total_subtotal.toFixed(2));
			$('#total_subtotal').val(total_subtotal.toFixed(2));
			$('#contract_price').val(total_subtotal.toFixed(2));
			$('#final_price').val(total_subtotal.toFixed(2));

			final_price_sum('rate');
		}else{
			return false;
		}
	}
	//根据选项计算价格 END
	/**
	 *计算销售价格
	 */
	function cal_discount_money(unit_price, amount, discount_rate){
		var product_discount = 0;
		if(discount_rate == 0){
			product_discount = 0;
		}else{
			product_discount = (unit_price * amount) * (discount_rate/100);
		}
		return parseFloat(product_discount).toFixed(2);
	}
	function final_price_sum(status){
		//产品合计
		var total_subtotal_val = $('#prime_price').val();
		//整单折扣
		var final_discount_rate = $('#final_discount_rate').val();
		if (status == 'contract_price') {
			//订单金额
			var final_price = $('#contract_price').val();
		} else {
			//订单金额
			var final_price = $('#final_price').val();
		}

		if (status == 'rate') {
			//过滤
			final_discount_rate = final_discount_rate.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
			final_discount_rate = final_discount_rate.replace(/^\./g,""); //验证第一个字符是数字
			final_discount_rate = final_discount_rate.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
			final_discount_rate = final_discount_rate.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
			final_discount_rate = final_discount_rate.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
			$('#final_discount_rate').val(final_discount_rate);

			if (final_discount_rate > 100) {
				$('#final_discount_rate').val('0.00');
				$('#final_discount_rate').focus();
				final_price_sum('rate');
				alert_crm('整单折扣不能大于100');
				return false;
			}

			final_price = parseFloat(total_subtotal_val*(1-final_discount_rate/100)).toFixed(2);
			$('#final_price').val(final_price);
		} else {
			//过滤
			final_price = final_price.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
			final_price = final_price.replace(/^\./g,""); //验证第一个字符是数字
			final_price = final_price.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
			final_price = final_price.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
			final_price = final_price.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数

			//整单折扣
			if(final_price == 0 || final_price == 0.00 || total_subtotal_val == 0 || total_subtotal_val == 0.00){
				final_discount_rate = '0.00';
			}else{
				final_discount_rate = parseFloat((total_subtotal_val-final_price)/total_subtotal_val*100).toFixed(2);
			}

			$('#final_discount_rate').val(final_discount_rate);
		}
		$('#contract_price').val(final_price);
		$('#final_price').val(final_price);
	}
</script>
<script type="text/javascript">
$("#dialog-file").dialog({
    autoOpen: false,
    modal: true,
	width: 800,
	maxHeight: 400,
	position: ["center",100],
	buttons: {
		"确定": function () {
		   $.ajax({
                cache: true,
                type: "POST",
                url:'{:U("file/getfiles")}',
                data:$('#uploadForm').serialize(),
                async: false,
                success: function(data) {
                   var result = data.data.file_list;
                   $('#filecontent').removeAttr('class');
                   var temp = '';
                   if(result){
                   		 $.each(result,function(k,v){
                   		 	temp += '<div class="showfile" id="del_'+v.file_id+'"><input type="hidden" name="file[]" value="'+v.file_id+'"/><img src="__PUBLIC__/productImg/'+v.pic+'">&nbsp;<span style="color:#646464;">'+v.name+'&nbsp;(&nbsp;'+v.size+'KB&nbsp;)</span>&nbsp;&nbsp;<a href="javascript:;" rel="'+v.file_id+'" onclick="del_file(this);"><img src="__PUBLIC__/img/delfile.png"/></a></div>';
                  		 });
                  		 $('#addfilediv').before(temp);
                  		 var old_file_num = Number($('#file_num').html());
                  		 var old_file_size = Number($('#file_size').html());
                  		 var new_file_num = old_file_num+data.data.file_num;
                  		 var new_file_size = old_file_size+data.data.file_size;
                  		 $('#file_num').html(new_file_num);
                  		 $('#file_size').html(new_file_size);
                   }

                }
            });
		   $(this).dialog("close");
		},
		"取消": function () {
			 $(this).dialog("close");
		}
	}
});

$(".addfile").click(function(){
	$('#dialog-file').dialog('open');
	$('#dialog-file').load('{:U("file/addlogfile")}');
});

//删除 函数
function del_obj(id){
    var module = 'contract';
    $.post("{:U('file/filedel')}",{file_id:id,module:module},function(data){
		if(data.status == 1){
			$('#del_'+id).remove();
			swal("删除成功！", "你的文件被删除了", "success");
			if($('.showfile').length > 0){
				return true;
			}else{
				$('#filecontent').addClass('hide');
			}
		}else{
		 	swal({
				title: "提示",
				text: data.info,
				type: "error"
			});
		}
		},"json"
	);
}
//删除
function del_file(obj){
	var id = $(obj).attr('rel');
	swal({
		title: "您确定要删除附件信息吗？",
		text: "删除后将无法恢复，请谨慎操作！",
		type: "warning",
		showCancelButton: true,
		confirmButtonColor: "#DD6B55",
		confirmButtonText: "删除",
		cancelButtonText: "取消",
		closeOnConfirm: false
	},
	function(isConfirm){
		if (isConfirm) {
			del_obj(id);
		}else{
			return false;
		}
	});
}
//全部删除 函数
function delall(){
	swal({
		title: "您确定要删除附件信息吗？",
		text: "删除后将无法恢复，请谨慎操作！",
		type: "warning",
		showCancelButton: true,
		confirmButtonColor: "#DD6B55",
		confirmButtonText: "删除",
		cancelButtonText: "取消",
		closeOnConfirm: false
	},
	function(isConfirm){
		if (isConfirm) {
			$('.showfile').each(function(){
				var id = $(this).find('input[type="hidden"]').val();
				del_obj(id);
			});
		}else{
			return false;
		}
	});
}

$(function () {
	$(".submit_file").click(function () {
		$("#file_btn").click();
    })
    $("#file_btn").on("change",function () {
        var dataform = new FormData();
        dataform.append("file",$('#file_btn')[0].files[0]);
        var filename = $('#file_btn')[0].files[0].name;
        var content = $('#file_btn')[0].files[0].size/1024 + 'kb';
        var filetype=$('#file_btn')[0].files[0].name.toLowerCase().split('.').splice(-1);
        console.log(filename+","+content+","+filetype);
        $(".file_list").append("<p>"+filename+"</p>");
        $.ajax({
            url:"",
            type:"post",
            data:dataform,
            success:function(data){

            },
            error:function(e){
                alert("错误！！");
                window.clearInterval(timer);
            }
        });
    })
})
</script>
<include file="Public:footer" />
